import time
import sys
import json
sys.path.append(r'.')
from DrissionPage import ChromiumPage

def load_param_datas_from_file(file_path):
    with open(file_path, "r", encoding='utf-8') as f:
        json_file_datas = json.loads(f.read())    # load的传入参数为字符串类型
        return json_file_datas

def item_url_list():
    json_file_datas = load_param_datas_from_file('item_url_list.data.json')
    port = json_file_datas['port']
    url = json_file_datas['url']
    urlFile = json_file_datas['urlFile']
    page = ChromiumPage(addr_or_opts='127.0.0.1:' + str(port))
    page.get(url)
    # 等待页面加载
    page.wait.load_start()
    with open(urlFile, "w") as file:
        file.write("")
    tbody_tag = page.ele('tag:tbody')
    if not tbody_tag:
        return

    table_trs = tbody_tag.eles('tag:tr')
    if not table_trs:
        return

    line = 0
    # 使用with语句打开文件，如果文件不存在则创建一个新的文件
    with open(urlFile, "w") as file:
        for tb_tr in table_trs:
            # 合计： 最后一行退出
            line = line +1
            if line >= len(table_trs):
                break

            tds = tb_tr.children()
            if len(tds) >= 3:
                td_3 = tb_tr.child(index=3)
                link_div = td_3.child(1).child(1).child(2)
                link = link_div.ele('tag:a')
                campaign_url = link.attr('href')
                file.write(campaign_url + "\n")

item_url_list()
